import { Link, useHistory } from 'react-router-dom'
import { useEffect, useRef } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Table,
  Tag,
  Space,
  Modal,
  DatePicker,
  message,
} from 'antd'
import { Channels } from '@/components/Channels'
import 'moment/locale/zh-cn'
import locale from 'antd/es/date-picker/locale/zh_CN'
import {
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons'
import { getChannels, getArticle, delclickDel } from '@/store/actions'
import img404 from '@/assets/error.png'
const { RangePicker } = DatePicker
const { confirm } = Modal

export const Article = () => {
  const dispatch = useDispatch()
  const history = useHistory()
  const paramsRef = useRef({})

  // 解构redux的数据
  const { page, pageSize, list, count } = useSelector((state) => state.article)

  // status	否		文章状态，0-草稿，1-待审核，2-审核通过，3-审核失败，不传为全部
  // 优化文章状态的处理
  const articleStatus = {
    0: { color: 'yellow', text: '草稿' },
    1: { color: '#ccc', text: '待审核' },
    2: { color: 'green', text: '审核通过' },
    3: { color: 'red', text: '审核失败' },
  }

  // 获得文章数据(频道列表/文章列表)
  useEffect(() => {
    dispatch(getChannels())
    dispatch(getArticle({}))
  }, [dispatch])

  // 数据列表
  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      render: (cover) => {
        return <img src={cover ?? img404} width={200} height={150} alt="" />
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
      width: 220,
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (data) => {
        const aridata = articleStatus[data]
        return <Tag color={aridata.color}>{aridata.text}</Tag>
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      // 因为该 列 不对应任何的数据（也就是没有 dataIndex 属性）
      // 所以，可以通过第一个参数 data 来拿到每一行的数据
      render: (data) => {
        return (
          <Space size="middle">
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              onClick={() => history.push(`/home/publish/${data.id}`)}
            />
            <Button
              type="primary"
              danger
              shape="circle"
              icon={<DeleteOutlined />}
              onClick={() => onClickDel(data.id)}
            />
          </Space>
        )
      },
    },
  ]

  // 删除文章
  const onClickDel = (id) => {
    // console.log(id)
    confirm({
      title: '温馨提示',
      icon: <ExclamationCircleOutlined />,
      content: '操作危险是否继续进行！',
      locale: locale,
      async onOk() {
        // console.log(paramsRef)
        await dispatch(delclickDel(id))
        message.success('删除文章成功', 1, async () => {
          await dispatch(getArticle(paramsRef.current))
        })
      },
    })
  }

  // 筛选表单完成提交
  const onSearch = (val) => {
    const { status, channel_id, date } = val

    const params = {}
    if (status !== -1) {
      params.status = status
    }
    // if (channel_id !== undefined) {
    if (typeof channel_id !== 'undefined') {
      params.channel_id = channel_id
    }

    // 日期范围
    if (typeof date !== 'undefined' && date !== null) {
      // if (date != undefined) {
      params.begin_pubdate = date[0].format('YYYY-MM-DD HH:mm:ss')
      params.end_pubdate = date[1].format('YYYY-MM-DD HH:mm:ss')
    }

    // 将组装好的 params 参数，存到 ref 对象中
    paramsRef.current = params

    // console.log('params:', params)
    dispatch(getArticle(params))
  }

  // 表格页数发生改变
  const onChangeSize = async (page, pageSize) => {
    // console.log(page, pagesize)
    const params = {
      ...paramsRef.current,
      page,
      per_page: pageSize,
    }

    await dispatch(getArticle(params))
  }

  return (
    <div>
      <Card
        title={
          <Breadcrumb separator=">">
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>内容管理</Breadcrumb.Item>
          </Breadcrumb>
        }
        style={{ marginBottom: 20 }}
      >
        <Form initialValues={{ status: -1 }} onFinish={onSearch}>
          <Form.Item label="状态" name="status">
            <Radio.Group>
              <Radio value={-1}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="频道" name="channel_id">
            <Channels width={290} />
          </Form.Item>
          <Form.Item label="日期" name="date">
            <RangePicker locale={locale} />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
          </Form.Item>
        </Form>
      </Card>

      <Card title={`根据筛选条件共查询到 ${count} 条结果：`}>
        {/* 
          rowKey="id" 表示使用数据源中哪个属性名来为 表格 指定 key 属性
        */}
        <Table
          rowKey="id"
          columns={columns}
          dataSource={list}
          pagination={{
            current: page,
            pageSize,
            total: count,
            showSizeChanger: true,
            position: ['bottomCenter'],
            onChange: onChangeSize,
          }}
        />
      </Card>
    </div>
  )
}
